using UnityEngine;

public class SpiderMove: MonoBehaviour
{
    private Camera _camera;
    private Vector2 _targetDirection;
    private float _changeDirectionCooldown;
    private float _speed;
    private float _rotationSpeed;

    private void Awake()
    {
        _camera = Camera.main;
        _targetDirection = Vector2.up;
        _speed = Random.Range(2, 5);
        _rotationSpeed = Random.Range(90, 180);
    }

    private void Update()
    {
        UpdateTargetDirection();
        RotateTowardsTarget();
        SetPosition();

        for (int i = 0; i < 10000; i++)
        {
            Mathf.Sqrt(5000);
        }
    }

    private void UpdateTargetDirection()
    {
        HandleRandomDirectionChange();
        HandleOffScreen();
    }

    private void HandleRandomDirectionChange()
    {
        _changeDirectionCooldown -= Time.deltaTime;
        if (_changeDirectionCooldown <= 0)
        {
            float angleChange = Random.Range(-90f, 90f);
            Quaternion rotation = Quaternion.AngleAxis(angleChange, Vector3.forward);
            _targetDirection = rotation * _targetDirection;
            _changeDirectionCooldown = Random.Range(1, 5);
        }
    }

    private void HandleOffScreen()
    {
        Vector2 screenPoint = _camera.WorldToScreenPoint(transform.position);

        if ((screenPoint.x < 0 && _targetDirection.x < 0) ||
            (screenPoint.x > _camera.pixelWidth && _targetDirection.x > 0))
        {
            _targetDirection = new Vector2(-_targetDirection.x, _targetDirection.y);
        }

        if ((screenPoint.y < 0 && _targetDirection.y < 0) ||
            (screenPoint.y > _camera.pixelHeight && _targetDirection.y > 0))
        {
            _targetDirection = new Vector2(_targetDirection.x, -_targetDirection.y);
        }
    }

    private void RotateTowardsTarget()
    {
        Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, _targetDirection);
        var rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
        transform.rotation = rotation;
    }

    private void SetPosition()
    {
        transform.Translate(transform.up * _speed * Time.deltaTime, Space.World);
    }
}